const { get, post } = require("../../utils/request");
const app = getApp();

Page({
  data: {
    activeTab: "all",
    activeTabIndex: 0,
    coupons: [], // 红包列表
    isLoading: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.loadCoupons();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("页面显示");
  },

  /**
   * 加载红包数据
   */
  loadCoupons: function () {
    this.setData({ isLoading: true });

    const loginStatus = app.checkLoginStatus();
    if (!loginStatus.isLoggedIn) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });
      setTimeout(() => {
        wx.navigateTo({
          url: "/pages/registration/registration",
        });
      }, 1500);
      return;
    }

    const userId = loginStatus.userInfo.id;

    // 获取用户的红包列表
    get(`/coupon/user/${userId}`)
      .then((res) => {
        console.log("接口返回数据:", res);
        if (res.code === 200) {
          const coupons = res.data || [];

          // 格式化日期
          coupons.forEach((item) => {
            const validTo = new Date(item.validTo);
            const createTime = new Date(item.createTime);

            item.formattedDate = this.formatDate(validTo);
            item.formattedCreateTime = this.formatDate(createTime);
          });

          this.setData({
            coupons: coupons,
            isLoading: false,
          });
        } else {
          wx.showToast({
            title: res.msg || "获取红包失败",
            icon: "none",
          });
          this.setData({ isLoading: false });
        }
      })
      .catch((err) => {
        console.error("获取红包异常:", err);
        wx.showToast({
          title: "获取红包失败",
          icon: "none",
        });
        this.setData({ isLoading: false });
      });
  },

  /**
   * 格式化日期
   */
  formatDate: function (date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    return `${year}-${month}-${day}`;
  },

  /**
   * 处理标签点击
   */
  handleTabTap: function (e) {
    const tab = e.currentTarget.dataset.tab;
    let tabIndex = 0;
    if (tab === "today") {
      tabIndex = 1;
    } else if (tab === "expiring") {
      tabIndex = 2;
    }
    this.setData({
      activeTab: tab,
      activeTabIndex: tabIndex,
    });
  },

  /**
   * 处理轮播切换
   */
  handleSwiperChange: function (e) {
    const index = e.detail.current;
    let tab = "all";
    if (index === 1) {
      tab = "today";
    } else if (index === 2) {
      tab = "expiring";
    }
    this.setData({
      activeTab: tab,
      activeTabIndex: index,
    });
  },

  /**
   * 前往使用红包
   */
  goToUse: function (e) {
    wx.switchTab({
      url: "/pages/venueReservation/venueReversation",
    });
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh: function () {
    this.loadCoupons();
    wx.stopPullDownRefresh();
  },
});
